<template>
  <div class="cain-tabs">
    <a-tabs
      v-model:activeKey="activeKey"
      type="editable-card"
      @change="tabsOnClick"
      @edit="onEdit"
      hide-add
    >
      <a-tab-pane
        v-for="pane in tabslist"
        :key="pane.path"
        :closable="pane.closable"
      >
        <template #tab>
          <span>
            <RedoOutlined />
            {{ pane.title }}
          </span>
        </template>
      </a-tab-pane>
    </a-tabs>
  </div>
</template>

<script lang="ts" setup>
import { computed, onMounted, ref } from "vue";
import { useRouter, useRoute, onBeforeRouteUpdate } from "vue-router";
import { Tabs } from "../../types/utils.interface";
import { useStore } from "vuex";
import { RedoOutlined } from "@ant-design/icons-vue";
// 实例化router
const router = useRouter();
// 实例化route值
const route = useRoute();
// 实例化store
const vuex = useStore();
// 获取vuex值
const tabslist = computed<Tabs[]>(() => {
  return vuex.state.tabslist;
});
// 监听路由修改
onBeforeRouteUpdate((to) => {
  const name: string = String(to.meta.title);
  const path: string = String(to.path);
  const is = tabslist.value.filter((v) => {
    return v.path === path;
  });
  if (is.length == 0) {
    const value: Tabs = {
      title: name,
      key: path + "1",
      path: path,
    };
    vuex.commit("setTabsList", value);
    activeKey.value = value.path;
  } else {
    activeKey.value = path;
  }
});

const activeKey = ref<string>(route.path);
// onMounted(() => {
//   activeKey.value =
// })

const newTabIndex = ref(0);
// tabs切换回调
const tabsOnClick = (e: Event) => {
  const tab = tabslist.value.filter((v) => {
    return v.path == String(e);
  });
  router.push(tab[0].path);
  activeKey.value = tab[0].path;
};
// 获取数据下标
const IndexOf = (val: string) => {
  let rindex = 0;
  tabslist.value.forEach((v, i) => {
    if (v.path == val) {
      rindex = i;
    }
  });
  return rindex;
};
// 删除
const remove = (targetKey: string) => {
  const i = IndexOf(targetKey);
  let lastIndex = 0;
  tabslist.value.forEach((pane, i) => {
    if (pane.path === targetKey) {
      lastIndex = i - 1;
    }
  });
  vuex.commit("updateTabsList", targetKey);
  if (tabslist.value.length && activeKey.value === targetKey) {
    router.push(tabslist.value[i - 1].path);

    if (lastIndex >= 0) {
      activeKey.value = tabslist.value[lastIndex].path;
    } else {
      activeKey.value = tabslist.value[0].path;
    }
  }
};

const onEdit = (targetKey: string | MouseEvent, action: string) => {
  if (action === "add") {
  } else {
    remove(targetKey as string);
  }
};
</script>

<style lang="scss">
.cain-tabs {
  padding: 10px;
  margin: 0 !important;
  .ant-tabs-nav {
    margin: 0 0 !important;
  }
}
</style>
images
